import React, { PureComponent, Fragment, Component } from 'react';
import { connect } from 'dva';
import {
  Row, Col, Card, Form, Input, Radio, Select, Icon, Button, Upload, message, InputNumber, Checkbox
,TimePicker} from 'antd';
import moment from 'moment';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Store.less';
import { imgPrex } from '../../utils/constData'

import { routerRedux } from 'dva/router';
import TextArea from 'antd/lib/input/TextArea';
import { Map, Polygon,Marker ,Polyline} from 'react-amap';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const { Option } = Select;
const format = 'HH:mm';
const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 18 } }
const timeItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 15 } }
const tailFormItemLayout = {
  wrapperCol: {
    xs: { span: 14, offset: 10 },
    sm: { span: 16, offset: 2 },
  },
};
let record = null
let map1
@connect(({ store, loading,storeDetail }) => ({
  store,
  loading: loading.models.store,
}))
@Form.create()
export default class EditStore extends PureComponent {
  constructor() {
    super()
    const _this = this
    const {serchCity} =this.state
    this.placesearch = null
    this.amapEvents = {
      created: (mapInstance) => {
        console.log('高德地图 Map 实例创建成功；如果你要亲自对实例进行操作，可以从这里开始。比如：');  
        console.log(mapInstance.getZoom());
        AMap.plugin('AMap.PlaceSearch', () => {
          _this.placesearch = new AMap.PlaceSearch({
            city: serchCity
          })
        })
      }
    };
    this.pevents = {
      created: (ins) => {
        ins.G.map.setFitView()
      }
    }
  }
  state = {
    mapKey: '893febe375679b9a415b19c7c52d206e',
    zoom: 12,
    center: {
      longitude: 121.473066, // 上海
      latitude: 31.231483
    },
    editOrAdd:'',
    markerPosition:{
      longitude:121.436938,
      latitude:31.231706
    },
    serchCity:null,
    timeSts:1,
  };

  componentDidMount() {
    this.props.dispatch({
        type: 'store/fetchFranList',
        payload: { "pageNum": "0", "pageSize": "0" }
      });
    if (this.props.match.params.storeId != 'new') {
      this.setState({
        editOrAdd:this.props.match.params.storeId,
        timeSts:1
      })
      this.props.dispatch({
        type: 'store/getStoreDetail',
        payload: { storeId: this.props.match.params.storeId },
        callback: (data) => this._setBackData(data)
      });
    }else{
      this.setState({
        record:null,
        timeSts:0
      })
    }
  }


_setBackData(data) {    
    this.setState({
      record: data, 
    })
  }

  submit() {
    console.log('this.props.form=====', this.props.form.getFieldsValue())
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;
      let values = { 
        ...fieldsValue,
        startTime:fieldsValue.startTime.format(format),
        endTime:fieldsValue.endTime.format(format),
          }
      console.log('表单提交数据：：：：？？？', values)
      if (values.storeId) {
        this.props.dispatch({
          type: 'store/editStore',
          payload: values,
          callback: () => this._callback()
        });
      } else {
        console.log('add')
        this.props.dispatch({
          type: 'store/addStore',
          payload: values,
          callback: () => this._callback()
        });
      }
    });
  }

  _callback() {
    this.props.dispatch(routerRedux.goBack())
  }

  //输入详细地址
  onInputDetail(e) {
    let addressDetail = e.target.value
    console.log(addressDetail)  
     this.placesearch && this.placesearch.search(addressDetail, (status,result) => {
      console.log(result)
      if(result.poiList.pois.length!=0 ||result.poiList.count!=0 ){
        const position =result.poiList.pois[0].location
        console.log(result.poiList.count)
        this.setState({
        serchCity:result.poiList.count,
        zoom:6,
        markerPosition:{
          longitude: position.lng, 
          latitude: position.lat
        }
      })
      }
      
    })
  }

  timeChange = (name, memt) => {
    console.log(memt.format(format))
      const { form } = this.props;
      form.setFieldsValue({
        [name]: memt.format(format),
      })
    }
changeSts=(e)=>{
  this.setState({
    timeSts:e.target.value
  })

}
 

  render() {
    const { form,store} = this.props;
    const {timeChange} =this;
    let { timeSts,editOrAdd,mapKey,VERSION,zoom,center,markerPosition,serchCity} = this.state;
    if(editOrAdd !='' || editOrAdd == 'new'){
      record = store.storeDetail
    }else{
      record=null
    }

    
    return (
      <PageHeaderLayout title="">
        <Card style={{width:750}} className={styles.Cardnopadd}>
          <Form >
            {editOrAdd !='' || editOrAdd == 'new' ?
              <FormItem {...formItemLayout} label="id" style={{ display: 'none' }}>
                {form.getFieldDecorator('storeId', {
                  rules: [{ required: true, message: '请输入id' }],
                  initialValue: record ? '' + record.storeId : null,
                })(<Input placeholder="请输入id" />)}
              </FormItem>
              :
              null
            }
            {
              editOrAdd !='' || editOrAdd == 'new' ? (<div className={styles.addmendfont}>编辑门店</div>):(<div className={styles.addmendfont}>新增门店</div>) 
            }
            
             <FormItem {...formItemLayout} label="门店名称">
              {form.getFieldDecorator('storeName', {
                initialValue: record ? record.storeName : null,
                rules: [{
                  required: true, message: '门店名字不能为空且不能超过20个字符',
                }]
              })(<Input placeholder="请输入门店名称20字以内" maxLength={20} />)}
            </FormItem>

            <FormItem {...formItemLayout} label="关联加盟商">
              {form.getFieldDecorator('franId', {
                rules: [{ required: true, message: '请选择加盟商' ,
              }],
                initialValue: record ? record.franId : null,
              })(
                <Select>
                   <Option value={null}>请选择</Option>
                  {(this.props.store.franList && this.props.store.franList.length > 0) && this.props.store.franList.map((item, i) => <Option key={i} value={item.franId}>{item.franName}</Option>)}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="关联员工账号">
              {form.getFieldDecorator('perPhone', {
                initialValue: record ? record.perPhones : null,
                rules: [{
                  required: true, message: '请输入正确的手机号,多个手机号以英文逗号隔开',
                  pattern:/^(1([38]\d|4[57]|5[0-35-9]|7[06-8])\d{8})(,(1([38]\d|4[57]|5[0-35-9]|7[06-8])\d{8}))*$/
                }]
              })(<Input placeholder="请输入员工手机号,多个手机号以英文逗号隔开"  />)}
            </FormItem>


            <Row>
              <Col span={22}>
                <div className={styles.lefttitle}>
                  <span>*</span>营业时间：
                </div>
                <div style={{ display: 'flex',float:'left',width:'30%' }}>
                  <FormItem {...timeItemLayout} label="">
                    {form.getFieldDecorator('startSts',{
                      initialValue: record ? record.startSts : 0,
                      rules: [{
                        required: true, message: '请输选择时间',
                      }]
                    })(<RadioGroup onChange={this.changeSts}>
                      <Radio value={0}>全天</Radio>
                        <Radio  value={1}>指定时间段</Radio>
                      </RadioGroup>
                    )}
                  </FormItem>
                </div>
                
                  <div style={{ display: 'flex',float:'left',marginRight:'2%'}}>
                    <FormItem {...timeItemLayout} label="">
                      {form.getFieldDecorator('startTime',{                     
                        initialValue: record ? moment(record.startTime,format) : moment('0:00',format),
                      })(
                      <TimePicker disabled={timeSts == 1  ? false:true}  format={format}
                      onChange={memt => {
                        timeChange(`startTime`, memt);
                      }}
                       />
                      )}
                    </FormItem>
                  </div>
                
                 
              
                  <div style={{ display: 'flex',float:'left' }}>
                    <FormItem {...timeItemLayout} label="">
                      {form.getFieldDecorator('endTime',{  
                        initialValue: record ? moment(record.endTime,format) : moment('23:59',format),
                      })(
                      <TimePicker disabled={timeSts == 1  ? false:true}
                      onChange={memt => {
                        timeChange(`endTime`, memt);
                      }}
                      format={format} />
                      )}
                    </FormItem>
                  </div>
                  
                
              </Col>
            </Row>

            <Row>
              <Col span={22}>
                <div className={styles.lefttitle}>
                  <span>*</span>门店地址：
                </div>
                <div style={{ display: 'flex',float:'left' ,marginRight:'2%'}}>
                  <FormItem {...timeItemLayout} label="">
                    {form.getFieldDecorator('province',{
                      initialValue: record ? record.province : null,
                      rules: [{ required: true, message: '请输入省份' }],
                    })(<Input placeholder="省份" style={{width:150}}  />)}
                  </FormItem>
                </div>
                <div style={{ display: 'flex',float:'left' ,marginRight:'2%' }}>
                  <FormItem {...timeItemLayout} label="">
                    {form.getFieldDecorator('city',{
                      initialValue: record ? record.city : null,
                      rules: [{ required: true, message: '请输入市辖区' }],
                    })(<Input placeholder="市辖区" style={{width:150}} /> )}
                  </FormItem>
                </div>
                <div style={{ display: 'flex',float:'left' }}>
                  <FormItem {...timeItemLayout} label="">
                    {form.getFieldDecorator('county',{
                      initialValue: record ? record.county : null,
                      rules: [{ required: true, message: '请输入区县' }],
                    })(<Input placeholder="区县" style={{width:150}} />)}
                  </FormItem>
                </div>
                
              </Col>
            </Row>

            <Row>
              <Col span={20} style={{float:'right'}}>
                <div className={styles.lefttitle}>
                  
                </div>
                  <FormItem {...formItemLayout} label="">
                    {form.getFieldDecorator('addressDetail',{
                      initialValue: record ? record.adressDetail : null,
                      rules: [{ required: true, message: '请输入详细地址' }],
                    })(<Input onChange={(e)=>this.onInputDetail(e)} placeholder="请输入详细地址，勿重复填写省市区信息，50字以内"  />)}
                  </FormItem>
              </Col>
            </Row>


            <div id="maps" className={styles.mapcont}>
              <Map amapkey={mapKey} events={this.amapEvents} version={VERSION} zoom={zoom} center={center}  useAMapUI>
                <Marker position={markerPosition} />
              </Map>            
            </div>

            <FormItem {...tailFormItemLayout}>
              <Button type="primary" htmlType="submit" onClick={() => this.submit()} loading={this.props.loading}>
                保存
              </Button>
              <Button type="danger" onClick={() => { this.props.dispatch(routerRedux.goBack()) }} style={{ marginLeft: '15px' }}>
                取消
              </Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderLayout >
    );
  }

}
